package com.yzx.lifeassistants.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.widget.PullRefreshLayout;
import com.baoyz.widget.PullRefreshLayout.OnRefreshListener;
import com.yzx.lifeassistants.GlobalParams;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.MyRunningAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.RunningInfo;
import com.yzx.lifeassistants.common.CommonConstant;
import com.yzx.lifeassistants.utils.DensityUtils;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;
import com.yzx.lifeassistants.view.widget.MySwipeMenuListView;

/**
 * @Description: 我的约跑
 * @author: yzx
 * @time: 2016-4-17 下午7:43:25
 */
public class MyRunningActivity extends BaseActivity implements OnClickListener {
	private ImageButton backBtn;// 返回按钮
	private PullRefreshLayout refreshLayout;// 下拉刷新
	private ImageView grayIV;//
	private MySwipeMenuListView runningLV;// 失物列表

	private CircularLoadingDialog dialog;
	private List<RunningInfo> dataList;// 失物列表
	private MyRunningAdapter adapter;// 适配器
	private List<Boolean> isList;//

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_running);
		init();
		initView();
		setListener();
		initSwipeMenuListView();
		initData();
	}

	/**
	 * 
	 * @Description: 初始化
	 */
	private void init() {

	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.my_running_back_btn);
		refreshLayout = (PullRefreshLayout) findViewById(R.id.my_running_pull_refresh_layout);
		grayIV = (ImageView) findViewById(R.id.my_running_gray_iv);
		runningLV = (MySwipeMenuListView) findViewById(R.id.my_running_lv);
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		// 下拉刷新
		refreshLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				queryMyRunning();
			}

		});
		// step 2. listener item click event
		runningLV
				.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(final int position,
							SwipeMenu menu, int index) {
						RunningInfo item = dataList.get(position);
						switch (index) {
						case 0:
							// open
							Intent intent = new Intent(MyRunningActivity.this,
									AddRunningActivity.class);
							intent.putExtra("from",
									CommonConstant.FROM_MY_RUNNING);
							Bundle bundle = new Bundle();
							bundle.putSerializable("runningInfo", item);
							intent.putExtras(bundle);
							startActivityForResult(intent,
									CommonConstant.REQUESTCODE_UPDATE_RUNNING);
							break;
						case 1:
							// delete
							dialog.show();
							item.delete(MyRunningActivity.this,
									new DeleteListener() {

										@Override
										public void onSuccess() {
											LogcatUtils.i("删除该约跑记录成功");
											dialog.dismiss();
											showToast("删除成功~", true);
											queryMyRunning();
										}

										@Override
										public void onFailure(int code,
												String message) {
											LogcatUtils.e("删除该约跑记录失败：" + code
													+ " " + message);
											dialog.dismiss();
											switch (code) {
											case 9010: {// 网络超时
												showToast("网络超时，请检查您的手机网络~",
														false);
												break;
											}
											case 9016: {// 无网络连接，请检查您的手机网络
												showToast("无网络连接，请检查您的手机网络~",
														false);
												break;
											}
											default: {
												showToast("删除失败，请重试~", false);
												break;
											}
											}
										}
									});
							break;
						}
						return false;
					}
				});

		// set SwipeListener
		runningLV.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

			@Override
			public void onSwipeStart(int position) {
				// swipe start
			}

			@Override
			public void onSwipeEnd(int position) {
				// swipe end
			}
		});

		// set MenuStateChangeListener
		runningLV
				.setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
					@Override
					public void onMenuOpen(int position) {

					}

					@Override
					public void onMenuClose(int position) {

					}
				});

		// other setting
		// listView.setCloseInterpolator(new BounceInterpolator());

		// test item long click
		runningLV
				.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {

						return false;
					}
				});
	}

	/**
	 * 
	 * @Description: 初始化能左划出打开/删除的ListView
	 */
	private void initSwipeMenuListView() {
		dataList = new ArrayList<RunningInfo>();
		isList = new ArrayList<Boolean>();
		adapter = new MyRunningAdapter(this, dataList);
		// SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new
		// SwingBottomInAnimationAdapter(
		// adapter);
		// swingBottomInAnimationAdapter.setAbsListView(runningLV);
		runningLV.setAdapter(adapter);
		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
						0xCE)));
				// set item width
				openItem.setWidth(DensityUtils
						.dp2px(MyRunningActivity.this, 90));
				// set item title
				openItem.setTitle("打开");
				// set item title fontsize
				openItem.setTitleSize(18);
				// set item title font color
				openItem.setTitleColor(Color.WHITE);
				// add to menu
				menu.addMenuItem(openItem);

				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				// set item width
				deleteItem.setWidth(DensityUtils.dp2px(MyRunningActivity.this,
						90));
				// set a icon
				deleteItem.setIcon(R.drawable.ic_delete);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		runningLV.setMenuCreator(creator);
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(this);
		queryMyRunning();
	}

	/**
	 * 
	 * @Description: 查询我的失物信息
	 */
	private void queryMyRunning() {
		dialog.show();
		BmobQuery<RunningInfo> query = new BmobQuery<RunningInfo>();
		query.addWhereEqualTo("username", GlobalParams.userInfo.getUsername());
		query.order("-updatedAt");// 按照修改时间升序
		query.findObjects(this, new FindListener<RunningInfo>() {

			@Override
			public void onSuccess(List<RunningInfo> runningInfos) {
				LogcatUtils.i("查询我的约跑记录成功");
				refreshLayout.setRefreshing(false);
				dialog.dismiss();
				dataList.clear();
				if (null == runningInfos || 1 > runningInfos.size()) {
					adapter.notifyDataSetChanged();
					showToast("暂未发布约跑信息~", true);
				} else {
					for (int i = 0; i < runningInfos.size(); i++) {
						isList.add(false);
					}
					dataList.addAll(runningInfos);
					adapter.notifyDataSetChanged();
				}
				if (0 < dataList.size()) {
					grayIV.setVisibility(View.VISIBLE);
				} else {
					grayIV.setVisibility(View.GONE);
				}
			}

			@Override
			public void onError(int code, String message) {
				LogcatUtils.e("查询我的约跑记录失败：" + code + " " + message);
				refreshLayout.setRefreshing(false);
				dialog.dismiss();
				switch (code) {
				case 101: {// 无数据
					grayIV.setVisibility(View.GONE);
					dataList.clear();
					adapter.notifyDataSetChanged();
					showToast("暂未发布约跑信息~", true);
					LogcatUtils.e("查询我的失物记录为空");
					break;
				}
				case 9010: {// 网络超时
					showToast("网络超时，请检查您的手机网络~", false);
					break;
				}
				case 9016: {// 无网络连接，请检查您的手机网络
					showToast("无网络连接，请检查您的手机网络~", false);
					break;
				}
				default: {
					showToast("获取失败，请刷新重试~", false);
					break;
				}
				}
			}

		});
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.my_running_back_btn: {
			finish();
			break;
		}
		default:
			break;
		}
	}

	/**
	 * @Description: 添加返回操作
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CommonConstant.REQUESTCODE_UPDATE_RUNNING) {
			if (resultCode == CommonConstant.RESULTCODE_UPDATE_RUNNING_OK) {
				showToast("约跑信息修改成功!", true);
				queryMyRunning();
			}
		}

	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.my_running_top_ll);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.my_running_top_ll);
		}

	}
}
